﻿using System.Net;
using System.Net.Sockets;
using System.Threading;
using System;
using System.Text;

namespace SocketClient
{
    class Program
    {
        private static byte[] result = new byte[1024];
        static void Main(string[] args)
        {
            //设定服务器IP地址
            start:
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                clientSocket.Connect(new IPEndPoint(ip, 8885)); //配置服务器IP与端口
                Console.WriteLine("连接服务器成功");

                string sendMessage = "client send Message Hellp" + DateTime.Now;
                clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage));
                Console.WriteLine("向服务器发送消息：{0}" + sendMessage);
            }
            catch
            {
                Console.WriteLine("连接服务器失败，重新尝试连接");
                Thread.Sleep(1000);    //等待1秒钟
                goto start;
            }

            while (true)
            {
                try
                {
                    //通过clientSocket接收数据
                    int receiveLength = clientSocket.Receive(result);
                    if (receiveLength != 0)
                        Console.WriteLine("接收服务器消息：{0}", Encoding.ASCII.GetString(result, 0, receiveLength));
                    else
                    {
                        clientSocket.Shutdown(SocketShutdown.Both);
                        clientSocket.Close();
                        goto start;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    clientSocket.Shutdown(SocketShutdown.Both);
                    clientSocket.Close();
                    break;
                }
            }
            Console.ReadLine();
        }
    }
}